java regex for alpha and spaces is including [ ] \

Posted by JayAvon on Stack Overflow See other posts from Stack Overflow or by JayAvon
Published on 2012-10-06T15:45:33Z Indexed on 2012/10/08 3:37 UTC
Read the original article Hit count: 125

Filed under:
|

This is my regex for my JTextField to not be longer than x characters and to not include anything other than letters or spaces. For some reason it is allowing [ ] and \ characters. This is driving me crazy. Is my regex wrong??

package com.jayavon.game.helper;

import java.awt.Toolkit;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class CharacterNameCreationDocument extends PlainDocument {
    private static final long serialVersionUID = 1L;
    private int limit;

    public CharacterNameCreationDocument(int limit) {
        super();
        this.limit = limit;
    }

    public void insertString(int offset, String  str, AttributeSet attr) throws BadLocationException {
        if (str == null || (getLength() + str.length()) > limit || !str.matches("[a-zA-z\\s]*")){
            Toolkit.getDefaultToolkit().beep();
            return;
        } else {
            super.insertString(offset, str, attr);
        }
    }
}

© Stack Overflow or respective owner

Related posts about java

Related posts about regex